package com.ryqg.jiaofu.utils;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;

import java.io.File;
import java.net.URL;

/**
 * OSS客户端管理类
 */
public class OssClient {
    
    // 京东云OSS配置
    private static final String ACCESS_KEY = "JDC_1AF876EB5BDA0EAB3E21597E7B4C";
    private static final String SECRET_KEY = "15D8ABE403855E5415FC54209C6630E0";
    private static final String ENDPOINT = "https://s3.cn-east-2.jdcloud-oss.com";
    private static final String REGION = "cn-east-2";
    
    // Bucket配置
    public static final String PRIVATE_BUCKET = "jiaofu-file";     // 私密bucket：存储PDF、PPT、Word、HTML文件
    public static final String PUBLIC_BUCKET = "jiaofu-images";   // 公开bucket：存储封面图
    
    private static volatile AmazonS3 s3Client;
    
    /**
     * 获取S3客户端实例（单例模式）
     */
    public static AmazonS3 getS3Client() {
        if (s3Client == null) {
            synchronized (OssClient.class) {
                if (s3Client == null) {
                    s3Client = createS3Client();
                }
            }
        }
        return s3Client;
    }
    
    /**
     * 创建S3客户端
     */
    private static AmazonS3 createS3Client() {
        ClientConfiguration config = new ClientConfiguration();
        
        AwsClientBuilder.EndpointConfiguration endpointConfig =
                new AwsClientBuilder.EndpointConfiguration(ENDPOINT, REGION);
        
        AWSCredentials awsCredentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
        AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);
        
        return AmazonS3Client.builder()
                .withEndpointConfiguration(endpointConfig)
                .withClientConfiguration(config)
                .withCredentials(awsCredentialsProvider)
                .disableChunkedEncoding()
                .build();
    }
    
    /**
     * 获取私密bucket名称
     */
    public static String getPrivateBucket() {
        return PRIVATE_BUCKET;
    }
    
    /**
     * 获取公开bucket名称
     */
    public static String getPublicBucket() {
        return PUBLIC_BUCKET;
    }


    public static boolean uploadFile(File file, String bucketName,String key){
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
            //设置文件元数据
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(file.length());
            objectMetadata.setContentType(getContentType(key));
            objectMetadata.setContentEncoding("UTF-8");
            objectMetadata.setCacheControl("public,max-age=604800");

            objectMetadata.addUserMetadata("upload-time",String.valueOf(System.currentTimeMillis()));

            putObjectRequest.setMetadata(objectMetadata);

            getS3Client().putObject(putObjectRequest);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static  String getUrl(String bucketName,String key){
        URL url = getS3Client().getUrl(bucketName, key);
        return url.toString();
    }

    /**
     * 根据文件名获取内容类型
     */
    private static String getContentType(String fileName) {
        String lowerName = fileName.toLowerCase();
        // 图片类型
        if (lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg")) return "image/jpeg";
        if (lowerName.endsWith(".png")) return "image/png";
        if (lowerName.endsWith(".gif")) return "image/gif";
        if (lowerName.endsWith(".bmp")) return "image/bmp";
        if (lowerName.endsWith(".webp")) return "image/webp";
        if (lowerName.endsWith(".svg")) return "image/svg+xml";
        if (lowerName.endsWith(".ico")) return "image/x-icon";

        // 视频类型（如果需要支持公开视频）
        if (lowerName.endsWith(".mp4")) return "video/mp4";
        if (lowerName.endsWith(".webm")) return "video/webm";
        if (lowerName.endsWith(".avi")) return "video/x-msvideo";

        // 音频类型（如果需要支持公开音频）
        if (lowerName.endsWith(".mp3")) return "audio/mpeg";
        if (lowerName.endsWith(".wav")) return "audio/wav";
        if (lowerName.endsWith(".ogg")) return "audio/ogg";

        // CSS/JS等前端资源
        if (lowerName.endsWith(".css")) return "text/css";
        if (lowerName.endsWith(".js")) return "application/javascript";

        // 文档类型
        if (lowerName.endsWith(".pdf")) return "application/pdf";
        if (lowerName.endsWith(".doc")) return "application/msword";
        if (lowerName.endsWith(".docx")) return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        if (lowerName.endsWith(".ppt")) return "application/vnd.ms-powerpoint";
        if (lowerName.endsWith(".pptx")) return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
        if (lowerName.endsWith(".xls")) return "application/vnd.ms-excel";
        if (lowerName.endsWith(".xlsx")) return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

        // 压缩文件
        if (lowerName.endsWith(".zip")) return "application/zip";
        if (lowerName.endsWith(".rar")) return "application/x-rar-compressed";
        if (lowerName.endsWith(".7z")) return "application/x-7z-compressed";

        // 文本文件
        if (lowerName.endsWith(".html") || lowerName.endsWith(".htm")) return "text/html; charset=utf-8";
        if (lowerName.endsWith(".txt")) return "text/plain; charset=utf-8";
        if (lowerName.endsWith(".json")) return "application/json; charset=utf-8";
        if (lowerName.endsWith(".xml")) return "application/xml; charset=utf-8";

        // 默认类型
        return "application/octet-stream";
    }

}
